package ar.com.e2solver;

import ar.com.e2solver.conf.PuzzleTheme;
import ar.com.e2solver.exception.BusinessException;
import ar.com.e2solver.solver.SolverResult;
import ar.com.e2solver.view.E2SolverView;

public class Main {

	public static void main(String args[]) {

		try {
			if (args.length == 1 && args[0].equals("-informe")) {
				runInforme();
			}

			PuzzleTheme puzzleTheme = new PuzzleTheme();
			new E2SolverView(new E2Solver(puzzleTheme));

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}

	/**
	 * Itera sobre la poblacion y las iteraciones y muestra el resultado en
	 * consola con formato csv. Se usa para recolectar datos y mostrar informe.
	 * 
	 * @throws Exception
	 */
	private static void runInforme() {
		PuzzleTheme puzzleTheme;
		try {
			puzzleTheme = new PuzzleTheme();
			E2Solver solver = new E2Solver(puzzleTheme);

			System.out.println(buildHeader());

			for (int i = 0; i < 3; i++) {
				System.out.println("");
				for (int poblacion = 50; poblacion <= 200; poblacion += poblacion) {
					for (int iteraciones = 2000; iteraciones <= 150000; iteraciones += iteraciones) {
						solver.getSolverConfiguration().setIterations(
								iteraciones);
						solver.getSolverConfiguration().setPopulationNumber(
								poblacion);
						SolverResult result = solver.run();

						System.out.println(buildResultRow(poblacion,
								iteraciones, result));
					}
				}
			}
		} catch (BusinessException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}

	}

	private static String buildResultRow(int poblacion, int iteraciones,
			SolverResult result) {

		StringBuffer sb = new StringBuffer();
		sb.append(poblacion).append(",");
		sb.append(iteraciones).append(",");
		sb.append(result.getBestIndividual().getFitnessValue()).append(",");
		sb.append(result.getAlgorithmDuration()).append(",");
		sb.append(result.getPopulationES()).append(",");
		sb.append(result.getPopulationVS()).append(",");
		sb.append(result.getMaxPossibleFitness());
		return sb.toString();
	}

	private static String buildHeader() {
		StringBuffer sb = new StringBuffer();
		sb.append("poblacion,");
		sb.append("iteraciones,");
		sb.append("bestIndividual,");
		sb.append("duration,");
		sb.append("ES,");
		sb.append("VS,");
		sb.append("MaxPossible");
		return sb.toString();
	}
}
